package com.mh.jdbc.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.mh.jdbc.entity.MBean;

public class BeanUtil {
	public static Map<String,Object> entity2Map(Object obj){
		SortedMap<String,Object> map = new TreeMap<>();
		Field[] fds = obj.getClass().getDeclaredFields();
		try {
			for(Field fd : fds){
				fd.setAccessible(true);
				map.put(fd.getName(), fd.get(obj));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return map;
	}
	/**
	 * @param map
	 * @param clz
	 * @return
	 */
	public static <T> T map2Entity(Map<String,Object> map,Class<T> clz){
		try {
			String key;
			Object val = null;
			T entity = clz.newInstance();
			Field[] fds = entity.getClass().getDeclaredFields();
			for(Field fd : fds){
				key = fd.getName();
				val = map.get(key);
				fd.setAccessible(true);
				fd.set(entity, val);
			}
			return entity;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}
	/**
	 * 集合强转
	 * @param mBeanList
	 * @param clz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> toTargetEntity(List<MBean> mBeanList,Class<T> clz){
		List<T> result = new ArrayList<>();
		Iterator<MBean> iterator = mBeanList.iterator();
		while(iterator.hasNext()){
			T  targetEntity = (T) iterator.next();
			result.add(targetEntity);
		}
		return result;
	}
}
